package handler

import (
	"github.com/gin-gonic/gin"
	"scenic-spot/model"
	"strconv"
)

func CreateScenic(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	data := model.Scenic{
		Title:   title,
		Content: content,
		Img:     img,
	}
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "添加成功",
		"data": data,
	})
}

func ListScenic(c *gin.Context) {
	page, _ := strconv.Atoi(c.PostForm("page"))
	Size, _ := strconv.Atoi(c.PostForm("page_size"))
	offset := (page - 1) * Size
	var scenic []model.Scenic
	var count int64
	err := model.DB.Model(&model.Scenic{}).Count(&count).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取条数失败",
		})
		return
	}
	err = model.DB.Offset(offset).Limit(Size).Find(&scenic).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": scenic,
	})
}

func DelScenic(c *gin.Context) {
	id := c.Query("id")
	var scenic model.Scenic
	err := model.DB.Where("id=?", id).Delete(&scenic).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})

}

func DetailScenic(c *gin.Context) {
	id := c.Query("id")
	var scenic model.Scenic
	err := model.DB.Where("id=?", id).First(&scenic).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取详情失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取详情成功",
		"data": scenic,
	})
}
